<?php
/**
 * Created by PhpStorm.
 * User: 张红雨
 * Date: 2018/8/6
 * Time: 14:45
 */
//------------------------------------------------下面是自定义 的函数
require('Oauth.php');//微认证类
function isLogin() {
    $header = $_SERVER;
    $token = $header['HTTP_UIDUSERNAMEKEY'];
    if (!$token) {
        fail_login('请登录后操作');
    }
    try {
        $decodedInfo = \Firebase\JWT\JWT::decode($token, C('COOKIE'), array('HS256'));
        if ($decodedInfo) {
            return $decodedInfo->uid;
        }
        return null;
    } catch (\Think\Exception $e) {
        return null;
    }
}

/**
 * 创建唯一 id字符串的公共方法
 */
function createIdStr() {
    $result = substr(str_shuffle(C('ID_STR')), 0, 15);
    return $result;
}

/**
 * 生成密码的盐
 * @return bool|string
 */
function make_salt() {
    $result = substr(str_shuffle(C('SALT_STR')), 0, 8);
    return $result;
}

/**
 * 对字符串进行加密
 * @param $a
 * @return string
 */
function jiami($a) {
    return md5($a);
}

/**
 * 批量对字符串去左右空格
 * @param array|string $data 要操作的字符串或者数组
 * @return array|string
 */
function get_trim_data($data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = get_trim_data($value);
        }
        return $data;
    } elseif (!is_bool($data)) {
        return trim($data);
    } else {
        return $data;
    }
}

/**
 * 自动对数据验证类型并过滤
 * @param string|array|number $data 要过滤的数据。支持String|Number
 * @param bool $decode 是否逆解析数据
 * @return string|array|number
 */
function get_auto_data($data, $decode = false) {
    // 数组类型
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = get_auto_data($value, $decode);
        }
        return $data;
    } // 数字
    elseif (is_numeric($data)) {
        if (false === strpos($data, '.')) {
            if ($data <= 2147483647 && $data >= -2147483647) {
                return intval($data);
            } else {
                return $data;
            }
        } else {
            return floatval($data);
        }
    } // 字符串
    elseif (is_string($data)) {
        if ($decode) {
            return get_de_html($data);
        } else {
            return get_en_html($data);
        }
    } // 其他
    else {
        return $data;
    }
}

/**
 * 过滤HTML代码
 * @param string $string
 * @return string
 */
function get_en_html($string) {
    return htmlspecialchars($string, ENT_QUOTES);
}

/**
 * 逆解析HTML代码
 * @param string $string
 * @return string
 */
function get_de_html($string) {
    return htmlspecialchars_decode($string, ENT_QUOTES);
}

/**
 * 成功返回
 * @param mixed $result 成功的数据
 */
function succeed($result, $msg = '请求成功') {
    if (is_string($result)) {
        if (preg_match("/^_(.*)_$/i", $result) || strstr($result, 'lang:')) {
            $result = L(str_replace('lang:', '', $result));
        }
    }
    header('Content-type: application/json');
    if ($result) {
        die(json_encode(array(
            'status'  => 200,
            'message' => $msg,
            'data'    => $result
        )));
    } else {
        die(json_encode(array(
            'status'  => 200,
            'message' => $msg
        )));
    }
}

/**
 * 错误返回
 * @param string $msg 错误消息
 */
function fail($msg) {
    if (preg_match("/^_(.*)_$/i", $msg) || strstr($msg, 'lang:')) {
        $msg = L(str_replace('lang:', '', $msg));
    }
    header('Content-type: application/json');
    if (!$msg) {
        $msg = '请求失败';
    }
    die(json_encode(array(
        'status'  => -1,
        'message' => $msg,
    )));
}

/**
 * 错误返回 status -3登录错误
 * @param string $msg 错误消息
 */
function fail_login($msg) {
    if (preg_match("/^_(.*)_$/i", $msg) || strstr($msg, 'lang:')) {
        $msg = L(str_replace('lang:', '', $msg));
    }
    header('Content-type: application/json');
    if (!$msg) {
        $msg = '登录过期';
    }
    die(json_encode(array(
        'status'  => -3,
        'message' => $msg,
    )));
}

/**
 * 表单错误
 * @param string $msg 错误消息
 * @param string $param 错误字段
 */
function fail_name($param = '', $msg = '参数错误') {
    if (preg_match("/^_(.*)_$/i", $msg) || strstr($msg, 'lang:')) {
        $msg = L(str_replace('lang:', '', $msg));
    }
    header('Content-type: application/json');
    die(json_encode(array(
        'status'  => -2,
        'message' => $msg,
        'param'   => $param
    )));
}

/**
 * 计算距现在过去多长时间
 * @param $ptime
 * @return false|float|int|string
 */
function getPastTime($ptime) {
    $time = time() - $ptime;
    if ($time >= 3600) {
        $hour = ceil($time / 3600) . "小时前";
    }
    if ($time >= 86400) {
        $hour = $time / 86400;
        if ($hour < 2) {
            $hour = "1" . "天前";
        }
        if ($hour >= 2 && $hour < 3) {
            $hour = "2" . "天前";
        }
        if ($hour >= 3) {
            $hour = date("Y-m-d", $ptime);
        }
    }
    if ($time < 3600) {
        if ($time / 60 < 0.5) {
            $hour = "刚刚";
        } else {
            $hour = ceil($time / 60) . "分钟前";
        }
    }
    return $hour;
}

/**
 * 获取格式化的
 * @param $time
 * @param $format
 * @return false|string
 */
function getFormatTime($time, $format) {
    $time_str = date($format, $time);
    return $time_str;
}

/**
 * 上传文件
 * @param $file
 * @param $maxSize
 * @param $exts
 * @param $rootPath
 * @return array
 */
function uploadFile($file, $maxSize, $exts, $rootPath, $isImg = true) {
    //解析图片信息
    $upload = new \Think\Upload();// 实例化上传类
    $upload->maxSize = $maxSize;// 设置附件上传大小
    $upload->exts = $exts;// 设置附件上传类型
    $upload->rootPath = $rootPath; // 设置附件上传根目录
    $upload->autoSub = true;
    $upload->subName = array('date', 'Ymd');
    // 上传文件
    $info = $upload->uploadOne($file);
    if (!$info) { // 上传错误提示错误信息
        return array(
            'uploadstatus' => -1,
            'msg'          => $upload->getError()
        );
    } else { // 上传成功
        $img_path = $rootPath . $info['savepath'] . $info['savename'];
        $thumb_path = $rootPath . $info['savepath'] . 'thumb_' . $info['savename'];
        if ($isImg) {
            $image = new \Think\Image();
            $image->open($img_path);
            $image->thumb(400, 400)->save($thumb_path);
            return array(
                'uploadstatus' => 200,
                'imgPath'      => $img_path,
                'thumbPath'    => $thumb_path,
            );
        }
        return array(
            'uploadstatus' => 200,
            'path'         => $img_path,
        );
    }
}

function getExt($filename) {
    $pos = strrpos($filename, '.');
    $ext = substr($filename, $pos);
    return $ext;
}

function getPathWithoutExt($filename) {
    $pos = strrpos($filename, '.');
    $path = substr($filename, 0, $pos);
    return $path;
}

/**
 * 网络请求 get
 * @param $url
 */
function request_get($url) {
    //1.初始化curl请求
    $ch = curl_init();
    //2..配置请求参数
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_URL, $url);//请求
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不直接输出数据
    //3.开始请求
    $res = curl_exec($ch);//获取请求结果
    if (curl_errno($ch)) {
        //        curl_error($ch)
        return false;
    }
    //4.关闭curl
    curl_close($ch);
    return $res;
}

/**
 * 获取微信openid
 * @param $loginCode
 * @return mixed
 */
function get_Openid($loginCode) {
    //1.请求url地址
    $appid = C('WX_APPID');
    $appsecret = C('WX_APPSECRET');
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&grant_type=authorization_code&js_code=' . $loginCode;
    $res = request_get($url);
    if ($res === false) {
        return false;
    }
    $arr = json_decode($res, true);//将结果转为数组
    return $arr['openid'];
}

/**
 * 下载远程文件
 * @param  string $url 网址
 * @param  string $filename 保存文件名
 * @param  integer $timeout 过期时间
 * return boolean|string
 */
function http_down($url, $filename, $timeout = 30) {
    $path = dirname($filename);
    if (!is_dir($path) && !mkdir($path, 0755, true)) {
        return false;
    }
    $fp = fopen($filename, 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    return $filename;
}

function sendWXMessage($template_id, $data, $form_id, $openid, $pages = 'pages/index/index') {
    //推送模板信息给置业顾问
    $send = new Oauth();
    //实例化类
    $result = $send->sendMessage($template_id, $data, $form_id, $openid, $pages);
    return $result;
}

// 过滤掉emoji表情
function filter_Emoji($str) {
    $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
        '/./u', function (array $match) {
        return strlen($match[0]) >= 4 ? '^*^' : $match[0];
    }, $str);
    return $str;
}

/*  $receiver 接收者的信息
        all 字符串 该产品下面的所有用户. 对app_key下的所有用户推送消息
        tag(20个)Array标签组(并集): tag=>array('昆明','北京','曲靖','上海');
        tag_and(20个)Array标签组(交集): tag_and=>array('广州','女');
        alias(1000)Array别名(并集): alias=>array('93d78b73611d886a74*****88497f501','606d05090896228f66ae10d1*****310');
        registration_id(1000)注册ID设备标识(并集): registration_id=>array('20effc071de0b45c1a**********2824746e1ff2001bd80308a467d800bed39e');
    */
//$content 推送的内容。
//$m_type 推送附加字段的类型(可不填) http,tips,chat....
//$m_txt 推送附加字段的类型对应的内容(可不填) 可能是url,可能是一段文字。
//$m_time 保存离线时间的秒数默认为一天(可不传)单位为秒
function JpushAlertSend($tilte = '', $content = '', $m_txt = '', $m_type = 'homework_new', $receiver = 'all', $m_time = 86400) {
    $base64 = base64_encode('d832409581bc315a2f145b92:93ecd4511aab5226f3d63efe');
    $header = array("Authorization:Basic $base64", "Content-Type:application/json");
    $data = array();
    $data['platform'] = 'all';          //目标用户终端手机的平台类型android,ios,winphone
    $data['audience'] = $receiver;      //目标用户
    $data['notification'] = array(
        "android" => array(
            "title"      => $tilte,
            "alert"      => $content,
            "builder_id" => 1,
            "extras"     => array(
                "action" => $m_type
            )
        ),
        "ios"     => array(
            "alert"  => $content,
            "sound"  => "default",
            "badge"  => "+1",
            "extras" => array(
                "action" => $m_type
            )
        )
    );
    //附加选项
    $data['options'] = array(
        "sendno"          => time(),
        "time_to_live"    => $m_time, //保存离线时间的秒数默认为一天
        "apns_production" => 1,        //指定 APNS 通知发送环境：0开发环境，1生产环境。
    );
    $param = json_encode($data);
    $res = push_curl($param, $header);
    if ($res) {       //得到返回值--成功已否后面判断
        return $res;
    } else {          //未得到返回值--返回失败
        return false;
    }
}

//推送的Curl方法
function push_curl($param = "", $header = "") {
    if (empty($param)) {
        return false;
    }
    $postUrl = 'https://bjapi.push.jiguang.cn/v3/push';
    $curlPost = $param;
    $ch = curl_init();                                      //初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);                 //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);           // 增加 HTTP Header（头）里的字段
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        // 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);                                 //运行curl
    curl_close($ch);
    return $data;
}
